package com.qf.interceptor;

import com.qf.common.constant.Constants;
import com.qf.entiy.po.LoginMerchant;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//springboot的拦截器，需要集成自HandlerInterceptorAdpater
public class LoginInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //当前处理器是Controller类中的方法时，才做相应的业务逻辑
        if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {
            Subject subject = SecurityUtils.getSubject();
            LoginMerchant loginMerchant = (LoginMerchant) subject.getPrincipal();
            if (loginMerchant == null) {
                response.sendRedirect("/"); //重定向到登录页面
                //throw new RuntimeException(ResultCode.LOGIN_ERROR.getDescription());
            }
            request.setAttribute(Constants.CURRENT_MERCHANT_USER, loginMerchant);
        }
        return super.preHandle(request, response, handler);
    }
}
